package Exercise;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Exercise1 {
    //扫描目标目录找到包含指定字符的文件，询问用户是否要删除
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要查找的目录:");
        String root = sc.next();
        File rootDir = new File(root);
        if(!rootDir.isDirectory()){
            System.out.println("您输入的不是有效的文件目录");
            return;
        }
        System.out.println("请输入要删除的文件名:");
        String token = sc.next();
        List<File> list = new ArrayList();
        search(rootDir, token, list);
        System.out.println("共找到" + list.size() + "个文件");
        for(File i : list){
            System.out.println("是否删除:" + i.getAbsolutePath());
            String set = sc.next();
            if(set.toLowerCase().equals("y")){
                i.delete();
            }
        }
    }

    private static void search(File rootDir, String token, List<File> list) {
        File[] file = rootDir.listFiles();
        if(file == null || file.length == 0){
            return;
        }
        for(File i : file){
            if(i.isDirectory()){
                search(i,token,list);
            } else if(i.getName().contains(token)){
                list.add(rootDir.getAbsoluteFile());
            }
        }
    }
}
